import { Module } from 'vuex'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo } from '@/api/login'
const state = {
  token: getToken(),
  userInfo: localStorage.userInfo ? JSON.parse(localStorage.userInfo) : {},
  roles: localStorage.roles ? JSON.parse(localStorage.roles) : []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INFO: (state, userInfo) => {
    // localStorage.userInfo = JSON.stringify(userInfo)
    state.userInfo = userInfo
  },
  SET_ROLES: (state, roles) => {
    // localStorage.roles = JSON.stringify(roles)
    state.roles = roles
  }
}

const actions = {
  // 登录
  async login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // commit('SET_INFO', userInfo)
      login(username, password).then(res => {
        const token = res.data
        setToken(token)
        commit('SET_TOKEN', token)
        resolve(username)
      })
    })
  },

  // 获取用户信息 ，如实际应用中 可以通过token通过请求接口在这里获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.userInfo?.id) {
        resolve(state.userInfo);
        return;
      }
      getInfo().then(res => {
        const { roles, isAdmin } = res.data
        commit('SET_INFO', res.data);
        if (isAdmin) {
          commit('SET_ROLES', 'admin');
          resolve(res.data)
        } else {
          commit('SET_ROLES', roles.map(o => o.roleKey));
          resolve(res.data)
        }
      })
    })
  },
  // 退出
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      removeToken()
      commit('SET_TOKEN', '')
      commit('SET_INFO', '')
      commit('SET_ROLES', '')
      resolve(null)
    })
  }
}

const user: Module<any, any> = {
  namespaced: true,
  state,
  actions,
  mutations
}

export default user
